package org.seedltd.upms.service.impl.detection;

import java.time.Duration;
import java.util.List;
import java.util.Map;

import org.apache.http.client.methods.HttpGet;
import org.seedltd.base.exception.BusinessException;
import org.seedltd.base.exception.RequestException;
import org.seedltd.core.utils.HttpUtils;
import org.seedltd.core.utils.JsonUtils;
import org.seedltd.core.utils.StringUtils;
import org.seedltd.redis.CacheKey;
import org.seedltd.redis.RedisService;
import org.seedltd.upms.model.detection.vo.CommodityInfo;
import org.seedltd.upms.service.detection.VendingMachineApiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.fasterxml.jackson.databind.JsonNode;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * 惠逸捷接口实现层
 *
 * @author laizuan
 * @version 1.0
 * @since 2021/9/23 16:56
 */
@Service
@Slf4j
public class HYJApiServiceImpl implements VendingMachineApiService {
    private final static String code = "result";
    private final static String data = "data";
    private final static String successCode = "200";
    private final static String authorization = "authorization";
    private final static String authorization_key = "hjy_authorization";

    @Value("${seedltd.hyj.username}")
    private String username;

    @Value("${seedltd.hyj.password}")
    private String password;

    @Value("${seedltd.hyj.login}")
    private String loginUrl;

    @Value("${seedltd.hyj.commodity}")
    private String queryCommodityUrl;

    @Value("${seedltd.hyj.notify-export}")
    private String notifyExportUrl;

    private final RedisService redisService;

    public HYJApiServiceImpl(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public String login() {
        Map<String, String> params = Map.of("userName", this.username, "password", password);
        String response = HttpUtils.sendGet(loginUrl, params);
        String token = this.getData(response, loginUrl).asText();
        if (StringUtils.isBlank(token)) {
            return null;
        }
        redisService.set(new CacheKey(authorization_key, Duration.ofDays(7)), token);
        return token;
    }

    private String getToken() {
        Object o = redisService.get(authorization_key);
        if (o == null) {
            throw new BusinessException("未获取到惠逸捷登入令牌，请联系客服");
        }
        return o.toString();
    }

    private JsonNode getData(String response, String url) {
        JsonNode jsonNode = JsonUtils.toJsonNode(response);
        if (!successCode.equals(jsonNode.get(code).asText())) {
            log.error("获取惠逸捷接口：{}，响应失败：{}", url, response);
            throw new RequestException("请求惠逸捷接口响应失败：%s", response);
        }
        return jsonNode.get(data);
    }

    @Override
    public List<CommodityInfo> queryCommodity(String machineId) {
        Map<String, String> params = Map.of("machineUuid", machineId);
        HttpGet httpGet = new HttpGet();
        httpGet.setHeader(authorization, getToken());
        String response = HttpUtils.sendGet(queryCommodityUrl, params, Map.of(authorization, getToken()));
        String data = this.getData(response, queryCommodityUrl).toString();
        return JsonUtils.toBeans(data, CommodityInfo.class);
    }

    @Override
    public String notifyExport(String machineUuid, String orderNo, String latticeId) {
        Map<String, Object> map = Map.of("cabinetId", "1", "latticeId", latticeId, "num", 1);
        List<Map<String, Object>> list = List.of(map);
        Map<String, Object> params = Map.of("list", list, "orderNum", DigestUtils.md5DigestAsHex(orderNo.getBytes()),
            "machineUuid", machineUuid);
        String response =
            HttpUtils.sendPostJson(notifyExportUrl, JsonUtils.toJsonString(params), Map.of(authorization, getToken()));
        return getData(response, notifyExportUrl).asText();
    }
}
